package com.example.qgmyzuul.filter;

import com.example.qgcommon.util.RedisUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

//登录验证
@Component
public class LoginFilter extends ZuulFilter {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        //除了登录请求，都需要验证
        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        System.out.println("requestURI:"+requestURI);

        if (!requestURI.endsWith("login")&&!requestURI.endsWith("/sendSms")){
            //检查是否登录过
            String token = request.getParameter( "token" );
            if (token==null||token.equals("")||!redisUtil.exist("token:"+token)){
                //没有正确登录的
                //让请求不要发
                currentContext.setSendZuulResponse( false );
                System.out.println("currentContext.setSendZuulResponse( false )---------------");


                currentContext.setResponseStatusCode(401);
            }
        }

        return null;
    }
}
